package com.dailyblue.java.project.smbms.address.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.commons.util.JsonResult;
import com.dailyblue.java.commons.util.ResultTool;
import com.dailyblue.java.project.smbms.address.bean.Address;
import com.dailyblue.java.project.smbms.address.mapper.AddressMapper;
import com.dailyblue.java.project.smbms.address.service.AddressService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Resource
    private AddressMapper addressMapper;

    @CachePut(cacheNames = "address", key = "#address.userId")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveAddress(Address address) {
        // 将当前用户其他地址修改成非常用
        addressMapper.updateAddress(address.getUserId());
        // 添加新地址
        save(address);
        return findAddressByUserId(address.getUserId());
    }

    @Cacheable(cacheNames = "address", key = "#userId")
    public JsonResult findAddressByUserId(int userId) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
        List<Address> list = list(wrapper);
        if (list == null || list.size() == 0) {
            return ResultTool.fail();
        }
        return ResultTool.success(list);
    }
}
